package com.googlecode.afdbaccess.web.common.servletfilter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class CacheHeaderFilter implements Filter {
    //private final static Logger log = Logger.getLogger(CacheHeaderFilter.class);
    
    private long seconds = 7*24*60*60;
    
    class ResponseWrapper extends HttpServletResponseWrapper {
        public ResponseWrapper(HttpServletResponse response) {
            super(response);
        }
        
        private void clearCacheHeaders() {
            // TODO: This will give empty headers for these in the response. See if there's a better way, to prevent this.
            setHeader("Expires", "");
            setHeader("Cache-Control", "");
        }
        
        @Override
        public void sendError(int sc) throws IOException {
            clearCacheHeaders();
            super.sendError(sc);
        }
        
        @Override
        public void sendError(int sc, String msg) throws IOException {
            //log.info("sendError");
            clearCacheHeaders();
            super.sendError(sc, msg);
        }
        
        @Override
        public void setStatus(int sc) {
            clearCacheHeaders();
            super.setStatus(sc);
        }
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //log.info("CacheHeaderFilter.doFilter");
        
        HttpServletResponse response = (HttpServletResponse)res;
        
        response.setDateHeader("Expires", System.currentTimeMillis() + seconds*1000);
        response.setHeader("Cache-Control", "public");

        chain.doFilter(req, new ResponseWrapper(response));        
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String secondsParam = filterConfig.getInitParameter("seconds");
        if(secondsParam != null) {
            this.seconds = Long.parseLong(secondsParam);
        }
    }
    
    @Override
    public void destroy() {
        // do nothing
    }
}